<template>
  <div class="cluster recovery">
    <a-card style="width: 100%">
      <p slot="title" class="cardTitles">
        <span>职工管理</span>
        <a-button type="primary" @click="downloadTemplate">模板</a-button>
        <a-upload
          name="file"
          :multiple="false"
          class="upload"
          accept=".csv"
          :customRequest="customRequest"
          :fileList="[]"
        >
          <a-button>上传</a-button>
        </a-upload>
        <a-button type="primary" @click="addManagement">新增</a-button>
      </p>
      <div class="formDiv">
        <a-form layout="inline">
          <a-row>
            <a-col :span="4">
              <a-form-item label="用户名称">
                <a-input v-model="account" type="text" style="width: 100px" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="姓名">
                <a-input v-model="name" type="text" style="width: 100px" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="性别">
                <a-select v-model="sex" style="width: 100px">
                  <a-select-option value="男">男</a-select-option>
                  <a-select-option value="女">女</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="所在站段">
                <!-- <a-input v-model="section" type="text" style="width: 100px" /> -->
                <a-select
                  v-model="section"
                  style="width: 100px"
                  @change="handleSectionChange"
                  :disabled="loginUserAuth === 3"
                >
                  <a-select-option
                    v-for="section in sectionData"
                    :key="section"
                  >
                    {{ section }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="车间/科室">
                <!-- <a-input v-model="shop" type="text" style="width: 100px" /> -->
                <a-select
                  v-model="shop"
                  style="width: 150px"
                  @change="handleShopChange"
                  :disabled="loginUserAuth === 3"
                >
                  <a-select-option v-for="shop in shopData" :key="shop">
                    {{ shop }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row style="margin-top: 10px">
            <a-col :span="4">
              <a-form-item label="班组名称">
                <!-- <a-input v-model="group" type="text" style="width: 100px" /> -->
                <a-select v-model="group" style="width: 100px">
                  <a-select-option v-for="group in groupData" :key="group">
                    {{ group }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="工号">
                <a-input v-model="jobCardID" type="text" style="width: 100px" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="岗位">
                <a-input v-model="post" type="text" style="width: 100px" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="岗位类别">
                <a-input v-model="postType" type="text" style="width: 100px" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="职名(工种)">
                <a-input
                  v-model="occupation"
                  type="text"
                  style="width: 100px"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item>
                <a-button type="primary" @click="search">搜索</a-button>
              </a-form-item>
              <a-form-item>
                <a-button @click="reset">重置</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="margin-top: 20px" class="table-content">
        <a-table
          bordered
          :columns="columns"
          :data-source="list"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
          @change="employeeChangePage"
        >
          <template slot-scope="text, record, index" slot="action">
            <a class="tools" @click="edit(record)">编辑</a>
            <a class="tools" type="link" @click="deletle(record, index)"
              >删除</a
            >
          </template>
        </a-table>
      </div>
    </a-card>
    <!-- 新增 -->
    <addModel
      :id="managementId"
      :type="managementType"
      @updateInform="updateInform"
      :managementVisible="managementVisible"
      @closeFunc="managementVisible = false"
    />
  </div>
</template>

<script>
import {
  getEmployeeList,
  deleteEmployee,
  getTree,
  addEmployee,
  downloadTemplate,
} from "@/api/employee";
import addModel from "components/configuration/employee/addModel";
import { paging } from "assets/js/mixin";
import jschardet from "jschardet";
import Papa from "papaparse";
export default {
  mixins: [paging],
  components: {
    addModel,
  },
  data() {
    return {
      loginUserAuth: JSON.parse(localStorage.getItem("userInfo")).auth,
      //三级联动
      sectionData: [],
      shopData: [],
      groupData: [],
      loading: false,
      //是否显示弹框
      managementVisible: false,
      managementId: null,
      managementType: 0, //0新增1是编辑
      //搜索字段
      account: "",
      section: "",
      shop: "",
      group: "",
      sex: "",
      jobCardID: "",
      occupation: "",
      postType: "",
      post: "",
      name: "",
      selectedRowKeys: [],
      columns: [
        {
          title: "用户名",
          dataIndex: "account",
          scopedSlots: { customRender: "objectName" },
        },
        {
          title: "姓名",
          dataIndex: "name",
        },
        {
          title: "性别",
          dataIndex: "sex",
        },
        {
          title: "工号",
          dataIndex: "workerID",
        },
        {
          title: "工作证号",
          dataIndex: "jobCardID",
        },
        {
          title: "所在站段",
          dataIndex: "section",
        },
        {
          title: "所在班组",
          dataIndex: "group",
        },
        {
          title: "所在车间/科室	",
          dataIndex: "shop",
        },
        {
          title: "职名（工种）",
          dataIndex: "occupation",
        },
        {
          title: "岗位",
          dataIndex: "post",
        },
        {
          title: "岗位类型",
          dataIndex: "postType",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      list: [],
      treeArr: {},
      formLayout: {
        spanCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      inputValue: "",
    };
  },
  mounted() {
    this.getTree();
    this.getEmployeeList();
  },
  methods: {
    downloadTemplate() {
      downloadTemplate()
        .then((res) => {
          var blob = new Blob([res.data], {
            type:
              ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
          });
          const url3 = window.URL.createObjectURL(blob);
          var filename = "职工模板" + ".csv";
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url3;
          link.setAttribute("download", filename);
          document.body.appendChild(link);
          link.click();
        })
        .catch((err) => {});
    },
    //上传用户信息接口
    addSubmit(arr) {
      addEmployee({
        employees: arr,
      })
        .then((res) => {
          if (res.data.ok) {
            this.$message.success("添加成功");
            this.getEmployeeList();
          } else {
            this.$message.error(res.data.errDatas[0].err);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //处理csv的数据
    dealData(data) {
      console.log(data);
      var employeeList = [];
      var fieldNameArr = data.shift();
      data.forEach((item2, index2) => {
        var obj = {};
        fieldNameArr.forEach((item, index) => {
          obj[item] = item2[index];
        });
        employeeList.push(obj);
      });
      return employeeList;
    },
    //上传职工信息
    customRequest(data) {
      const types = data.file.name.split(".")[1];
      const fileType = ["csv"].some((item) => item === types);
      if (!fileType) {
        this.$message.error("格式错误！请重新选择");
        return;
      }
      let fileObj = data.file; // 相当于input里取得的files
      let fReader = new FileReader();
      fReader.readAsDataURL(fileObj);
      fReader.onload = (evt) => {
        // 检查编码
        let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(fileObj, {
          encoding,
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
              //删除第一行汉字表头
              data.shift();
            }
            var employeeData = this.dealData(data);
            this.addSubmit(employeeData);
          },
        });
      };
    },
    // 检查编码，引用了 jschardet
    checkEncoding(base64Str) {
      // 这种方式得到的是一种二进制串
      let str = atob(base64Str.split(";base64,")[1]);
      // 要用二进制格式
      let encoding = jschardet.detect(str);
      encoding = encoding.encoding;
      if (encoding == "windows-1252") {
        // 有时会识别错误（如UTF8的中文二字）
        encoding = "ANSI";
      }
      return encoding;
    },
    handleSectionChange() {
      this.shop = "";
      this.group = "";
      var shopArr = [];
      var groupArr = [];
      for (const key in this.treeArr[this.section]) {
        shopArr.push(key);
      }
      for (const key2 in this.treeArr[this.section][shopArr[0]]) {
        groupArr.push(key2);
      }
      this.shopData = shopArr;
      this.groupData = groupArr;
    },
    handleShopChange() {
      this.group = "";
      var groupArr = [];
      for (const key2 in this.treeArr[this.section][this.shop]) {
        groupArr.push(key2);
      }
      this.groupData = groupArr;
      console.log(this.groupData);
    },
    //获取树结构
    getTree() {
      getTree()
        .then((res) => {
          this.treeArr = res.data.data;
          var sectionArr = [];
          var shopArr = [];
          var groupArr = [];
          for (const key in this.treeArr) {
            sectionArr.push(key);
          }
          for (const key in this.treeArr[sectionArr[0]]) {
            shopArr.push(key);
          }
          for (const key2 in this.treeArr[sectionArr[0]][shopArr[0]]) {
            groupArr.push(key2);
          }
          this.sectionData = sectionArr;
          //根据权限初始化数据
          if (this.loginUserAuth === 3) {
            this.section = JSON.parse(localStorage.getItem("userInfo")).section;
            this.shop = JSON.parse(localStorage.getItem("userInfo")).shop;
            this.handleShopChange();
          }
          // this.shopData = shopArr;
          // this.groupData = groupArr;
          // this.section = sectionArr[0];
          // this.shop = shopArr[0];
          // this.group = groupArr[0];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除用户信息
    deletle(record, index) {
      console.log(index);
      var _this = this;
      this.$confirm({
        title: "确定要删除该条职工信息吗？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          deleteEmployee(record.id)
            .then((res) => {
              if (res.data.ok) {
                _this.$message.success("删除成功");
                _this.getEmployeeList();
              } else {
                _this.$message.error(res.data.errDatas[0].err);
              }
            })
            .catch((err) => {
              _this.$message.destroy();
              _this.$message.error(err);
            });
        },
      });
    },
    //保存修改数据后刷新列表 关闭抽屉
    updateInform() {
      this.managementVisible = false;
      this.getEmployeeList();
    },
    //搜索
    search() {
      this.pageNum = 1;
      this.pagination.current = 1;
      this.getEmployeeList();
    },
    //重置
    reset() {
      this.pageNum = 1;
      this.pagination.current = 1;
      this.account = "";
      this.group = "";
      this.sex = "";
      this.jobCardID = "";
      this.occupation = "";
      this.post = "";
      this.postType = "";
      this.name = "";
      if (this.loginUserAuth === 3) {
        this.section = JSON.parse(localStorage.getItem("userInfo")).section;
        this.shop = JSON.parse(localStorage.getItem("userInfo")).shop;
        this.handleShopChange();
      }else{
        this.section = "";
        this.shop = "";
      }
      this.getEmployeeList();
    },
    onSelectChange(selectedRowKeys) {
      //列表多选操作
      this.selectedRowKeys = selectedRowKeys;
    },
    addManagement() {
      this.managementVisible = true;
      this.managementType = 0;
    },
    //编辑单个员工
    edit(record) {
      this.managementVisible = true;
      this.managementType = 1;
      this.managementId = record.id;
    },
    //分页操作
    employeeChangePage(pagination) {
      this.pageNum = pagination.current;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getEmployeeList();
    },
    getEmployeeList() {
      this.loading = true;
      var params = {
        page: this.pageNum,
        limit: this.pageSize,
        account: this.account,
        section: this.section,
        shop: this.shop,
        group: this.group,
        sex: this.sex,
        jobCardID: this.jobCardID,
        occupation: this.occupation,
        post: this.post,
        postType: this.postType,
        name: this.name,
      };
      getEmployeeList(params)
        .then((res) => {
          this.list = res.data.employees;
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
  },
};
</script>

<style lang="stylus" scoped>
.formDiv {
  .lable {
    margin-right: 10px;
  }
}

.upload {
  float: right;
}

.recovery {
  height: 100%;
}

.table-content {
  height: calc(100% - 138px);
  overflow: auto;
}

.ant-card-body {
  height: 100%;
}
</style>